package repository

import (
	"context"
	"demo/domain/model"
	"demo/domain/model/vo"
	"demo/infra/db"

	"gorm.io/gorm"
)

type urlMapRepository struct {
	db *gorm.DB
}

func (u urlMapRepository) FindAll(ctx context.Context) (*[]model.UrlMap, error) {
	var entity []model.UrlMap
	err := u.db.WithContext(ctx).Find(&entity, "deleted=?", 0).Error
	return &entity, err
}

func (u urlMapRepository) FindByCompressCode(ctx context.Context, compressCode string) (*model.UrlMap, error) {
	var entity model.UrlMap
	err := u.db.WithContext(ctx).Find(&entity, "compress_code=?", compressCode).Error
	return &entity, err
}

func (u urlMapRepository) PageFindByCondition(ctx context.Context, query *vo.UrlMapPageMapCondition) ([]vo.UrlMapPageResult, int64, error) {
	tx := u.db.WithContext(ctx).Model(&vo.UrlMapPageResult{}).
		Where("deleted = 0 and source = ?", query.Source)
	// 动态条件
	if query.ShortUrl != "" {
		tx = tx.Where("short_url = ?", query.ShortUrl)
	}
	if query.LongUrl != "" {
		tx = tx.Where("long_url = ?", query.LongUrl)
	}
	if query.Description != "" {
		tx = tx.Where("description like ?", "%"+query.Description+"%")
	}
	if query.Creator != "" {
		tx = tx.Where("creator = ?", query.Creator)
	}
	if query.Editor != "" {
		tx = tx.Where("editor = ?", query.Editor)
	}
	// 统计总数
	var total int64
	if err := tx.Count(&total).Error; err != nil {
		return nil, 0, err
	}
	// 查询领域实体列表
	var entities []vo.UrlMapPageResult
	offset := (query.PageNum - 1) * query.PageSize
	if err := tx.
		Order("edit_time DESC").
		Limit(query.PageSize).
		Offset(offset).
		Find(&entities).Error; err != nil {
		return nil, 0, err
	}
	// 直接返回领域实体，不做DTO转换
	return entities, total, nil
}

func (u urlMapRepository) Update(ctx context.Context, entity *model.UrlMap) error {
	rdb := db.GetDB(ctx, u.db)
	return rdb.WithContext(ctx).Model(entity).Select("long_url", "long_url_digest", "description",
		"editor", "version").Updates(entity).Error
}

func (u urlMapRepository) FindById(ctx context.Context, id int64) (*model.UrlMap, error) {
	var entity model.UrlMap
	err := u.db.WithContext(ctx).Find(&entity, "id=?", id).Error
	return &entity, err
}

func (u urlMapRepository) Save(ctx context.Context, entity *model.UrlMap) error {
	rdb := db.GetDB(ctx, u.db)
	return rdb.WithContext(ctx).Create(entity).Error
}

// NewUrlMapRepository 创建一个新的 Repository 实例
func NewUrlMapRepository(db *gorm.DB) model.UrlMapRepository {
	return &urlMapRepository{db: db}
}
